<!DOCTYPE html>
<html lang='en'>

<head>
    <meta charset='UTF-8'>
    <meta name='viewport' content='width=device-width, initial-scale=1.0'>
    <title>生成四位数的验证码</title>
    <link rel='stylesheet' href='//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.6.0/styles/default.min.css'>
    <script src='//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.6.0/highlight.min.js'></script>
</head>

<body>
    <button>换一个</button>
    <p class="code"></p>
    <pre>
        <code style='max-height: 400px;'>
            let updateCodeBtn = document.querySelector('button')
            let showCode = document.querySelector('.code')
            let code = null
            updateCodeBtn.addEventListener('click',() => {
                code = randomCode()
                showCode.innerText = code
                console.log('随机生成的验证码为', code);
            })
            /**
            * 生成四位数验证码
            * 
            */
            let randomStr = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' // 62位长度
            //    生成指定范围内的随机整数
            function randomMath(min, max) {
                return Math.round(Math.random() * (max - min) + min)
            }
            //    生曾随机验证码  --> len 生成验证码的位数默认为4位
            let randomCode = (len = 4) => {
                let str = ''
                for (let i = 0; i < len; i++) {
                    str += randomStr[randomMath(0, 61)]
                }
                return str
            }

            code = randomCode()
            showCode.innerText = code
            console.log('字符串长度', randomStr.length);
            console.log('随机生成的验证码为', code);
        </code>
     </pre>
    <script> hljs.highlightAll(); </script>
    <script>
        let updateCodeBtn = document.querySelector('button')
        let showCode = document.querySelector('.code')
        let code = null
        updateCodeBtn.addEventListener('click',() => {
            code = randomCode()
            showCode.innerText = code
            console.log('随机生成的验证码为', code);
        })
        /**
         * 生成四位数验证码
         * 
        */
        let randomStr = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' // 62位长度
        //    生成指定范围内的随机整数
        function randomMath(min, max) {
            return Math.round(Math.random() * (max - min) + min)
        }
        //    生曾随机验证码  --> len 生成验证码的位数默认为4位
        let randomCode = (len = 4) => {
            let str = ''
            for (let i = 0; i < len; i++) {
                str += randomStr[randomMath(0, 61)]
            }
            return str
        }

        code = randomCode()
        showCode.innerText = code
        console.log('字符串长度', randomStr.length);
        console.log('随机生成的验证码为', code);
    </script>
</body>

</html>